<template>
  <a-modal
    v-model="visibleSet"
    title="赏金设置"
    @ok="handleOk"
    :confirm-loading="confirmLoading"
    @cancel="$emit('update:visibleSet', false)"
    :width="700"
  >
    <a-form :form="form">
      <a-form-item :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }">
        <a-switch :checked="switchs" @change="switchs = !switchs" /> {{ switchs ? "已开启" : "已关闭" }}赏金规则
      </a-form-item>
      <a-form-item label="赏金金额" :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }">
        <a-input-number
          :disabled="!switchs"
          :min="0"
          placeholder="请输入"
          v-decorator="['empMoneyReward', { rules: [{ required: switchs, message: '赏金金额不能为空' }] }]"
        />
      </a-form-item>
      <div v-for="(k, i) in form.getFieldValue('keys')" :key="i">
        <a-form-item label="工作满" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }" style="width: 38%; float: left; z-index: 10">
          <a-input-number
            :disabled="!switchs"
            :min="0"
            placeholder="请输入"
            v-decorator="[
              `workingTime${i}`,
              {
                validateTrigger: ['change', 'blur'],
                rules: [
                  {
                    required: switchs,
                    whitespace: true,
                    message: '该项不能为空'
                  }
                ]
              }
            ]"
          />
        </a-form-item>
        <a-form-item :label-col="{ span: 0 }" :wrapper-col="{ span: 23 }" :required="false" style="width: 32%; float: left; z-index: 10">
          <a-select style="width: 76%; margin-right: 6%" :disabled="!switchs" v-model="timeType">
            <a-select-option value="1"> 天 </a-select-option>
            <a-select-option value="2"> 月 </a-select-option>
          </a-select>
          发放
        </a-form-item>
        <a-form-item :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }" :required="false" style="width: 30%; float: left; z-index: 10">
          <a-input-group compact>
            <a-input-number
              :disabled="!switchs"
              :min="0"
              placeholder="请输入"
              style="width: 56%"
              v-decorator="[
                `grantCount${i}`,
                {
                  validateTrigger: ['change', 'blur'],
                  rules: [
                    {
                      required: switchs,
                      whitespace: true,
                      message: '该项不能为空'
                    }
                  ]
                }
              ]"
            />
            <a-select :disabled="!switchs" v-model="grantType" class="grantType">
              <a-select-option value="1"> % &nbsp; </a-select-option>
              <a-select-option value="2"> 元 &nbsp; </a-select-option>
            </a-select>
            <a-icon
              :style="{ color: switchs ? '#000000' : '#d9d9d9', margin: '10px 0 0 10px' }"
              type="delete"
              @click.stop="remove(k)"
              v-if="form.getFieldValue('keys').length > 1"
            />
          </a-input-group>
        </a-form-item>
      </div>
      <a-form-item style="text-align: center">
        <a-button style="width: 120px" :disabled="!switchs" @click="add"> <a-icon type="plus" /> 添加阶段 </a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
// import moment from "moment";
import { postSaveBrokerOrEmpPost, putRecruitInfos } from "../api";
export default {
  props: {
    visibleSet: {
      type: Boolean,
      default: false
    },
    selectedListTempString: {
      type: Array,
      default: () => []
    },
    id: {
      type: String,
      default: ""
    },
    val: {
      type: String,
      default: ""
    },
    empMoneyReward: {
      type: Number,
      default: 0
    },
    empRuleIsOpen: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // form: this.$form.createForm(this, { keys: [{ date: "", money: "" }] }),
      switchs: true,
      confirmLoading: false,
      timeType: "1",
      grantType: "1"
    };
  },
  watch: {
    visibleSet(val) {
      if (val) {
        if (this.val) {
          const arr = JSON.parse(this.val);
          this.timeType = arr[0].timeType;
          this.grantType = arr[0].grantType;
          this.form.getFieldDecorator("keys", {
            initialValue: arr,
            preserve: true
          });
          this.switchs = this.empRuleIsOpen;
          setTimeout(() => {
            this.form.setFieldsValue({
              empMoneyReward: this.empMoneyReward
            });
            arr.forEach((e, i) => {
              this.form.setFieldsValue({
                [`workingTime${i}`]: e.workingTime,
                [`grantCount${i}`]: e.grantCount
              });
            });
          });
        } else {
          this.form.resetFields();
          setTimeout(() => {
            this.form.getFieldDecorator("keys", {
              initialValue: [{ workingTime: "", timeType: "", grantCount: "", grantType: "" }],
              preserve: true
            });
          });
        }
      }
    }
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, {});
    this.form.getFieldDecorator("keys", {
      initialValue: [{ workingTime: "", timeType: "", grantCount: "", grantType: "" }],
      preserve: true
    });
  },
  methods: {
    handleOk() {
      this.form.validateFields((err, values) => {
        if (this.switchs) {
          if (!err) {
            this.setValue(values);
          }
        } else {
          this.setValue(values);
        }
      });
    },
    setValue(values) {
      let num = 0;
      let s = true;
      values.keys.forEach((e, i) => {
        e.timeType = this.timeType;
        e.grantType = this.grantType;
        e.workingTime = values[`workingTime${i}`];
        e.grantCount = values[`grantCount${i}`];
        num += parseFloat(e.grantCount);
      });
      if (this.switchs) {
        if (this.grantType === "1") {
          if (num > 100) {
            s = false;
            this.$message.error("百分比总和不能大于100%");
          }
        }
        if (this.grantType === "2") {
          if (num > values.empMoneyReward) {
            s = false;
            this.$message.error("金额总和不能大于赏金金额");
          }
        }
      }

      if (s) {
        if (this.id) {
          this.onPutRecruitInfos(values);
        } else {
          this.onPostSaveBrokerOrEmpPost(values);
        }
      }
    },
    async onPutRecruitInfos(v) {
      try {
        await putRecruitInfos({
          empRuleIsOpen: this.switchs,
          empMoneyReward: v.empMoneyReward,
          empRule: JSON.stringify(v.keys),
          id: this.id
        });
        this.$notification.success({ message: "修改成功" });
        this.$emit("upDate");
        this.$emit("update:visibleSet", false);
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    async onPostSaveBrokerOrEmpPost(v) {
      try {
        await postSaveBrokerOrEmpPost({
          empRuleIsOpen: this.switchs,
          empMoneyReward: v.empMoneyReward,
          empRule: JSON.stringify(v.keys),
          recruitInfoIds: this.selectedListTempString,
          copyType: 2
        });
        this.$notification.success({ message: "添加成功" });
        this.$emit("upDate");
        this.$emit("update:visibleSet", false);
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    remove(k) {
      if (!this.switchs) return;
      const { form } = this;
      const keys = form.getFieldValue("keys");
      if (keys.length === 1) {
        return;
      }
      setTimeout(() => {
        form.setFieldsValue({
          keys: keys.filter(key => key !== k)
        });
      });
    },

    add() {
      const { form } = this;
      const keys = form.getFieldValue("keys");
      const nextKeys = keys.concat([{ workingTime: "", timeType: "", grantCount: "", grantType: "" }]);
      form.setFieldsValue({
        keys: nextKeys
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.grantType {
  ::v-deep.ant-select-selection {
    border-radius: 0 4px 4px 0 !important;
  }
}
</style>
